package com.poh.controller;

import com.poh.pojo.Course;
import com.poh.pojo.User;
import com.poh.service.impl.CourseServiceImpl;
import com.poh.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.List;

@Controller
public class CourseController {
    @Autowired
    UserServiceImpl userService;
    @Autowired
    CourseServiceImpl courseService;

    @GetMapping("/getCourse")
    public String getCourse(HttpSession session, Model model) {
        User user = (User) session.getAttribute("user");
        List<Course> studyCourse = courseService.getCourseByUserId(user.getUserId());
        List<Course> learnCourse = courseService.getCourseByTeach(user.getUserId());
        model.addAttribute("studyCourse", studyCourse);
        model.addAttribute("learnCourse", learnCourse);
        return "index";
    }



    @GetMapping("/editCourse")
    public String toEditCourse() {

        return "/course/editCourse";
    }



    @PostMapping("/uploadCourseImg")
    public String uploadCourseImg(@RequestPart("courseImg") MultipartFile courseImg,
                                  HttpSession session) throws IOException {
        Course course = (Course) session.getAttribute("course");
        if (!courseImg.isEmpty()) {
            String originalFilename = courseImg.getOriginalFilename();
            courseImg.transferTo(new File("F:\\JavaWeb\\Course_SpringBoot\\src\\main\\resources\\static\\img\\" + originalFilename));
            courseService.updateImgByCourseId(course.getCourseId(), originalFilename);
            course.setCourseImg(originalFilename);
            session.setAttribute("course", course);
            return "redirect:editCourse";
        }
        return "redirect:editCourse";
    }



}
